package com.leyou.service;

import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.mapper.SpecParamMapper;
import com.leyou.item.pojo.SpecGroup;
import com.leyou.item.pojo.SpecParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@SuppressWarnings("ALL")
@Service
public class SpecificationService {

    @Autowired
    private SpecGroupMapper specGroupMapper;

    @Autowired
    private SpecParamMapper specParamMapper;

    /**
     * 根据根类id查询分组
     * @param id
     * @return
     */
    public List<SpecGroup> queryGroupsById(Long id){
        Example example = new Example(SpecGroup.class);
        example.createCriteria().andEqualTo("cid",id);
        return this.specGroupMapper.selectByExample(example);
    }

    /**
     * 根据条件查询规格参数
     * @param gid
     * @return
     */
    public List<SpecParam> queryParams(Long gid){
        Example example = new Example(SpecParam.class);
        example.createCriteria().andEqualTo("groupId",gid);
        return this.specParamMapper.selectByExample(example);
    }


    /**
     * 根据gid查询规格参数
     * @param gid
     * @return
     */
    public List<SpecParam> queryParams(Long gid, Long cid, Boolean generic, Boolean searching) {
        SpecParam record = new SpecParam();
        record.setGroupId(gid);
        record.setCid(cid);
        record.setGeneric(generic);
        record.setSearching(searching);

        Example example = new Example(SpecParam.class);
        example.createCriteria().andEqualTo("groupId",gid)
                                .andEqualTo("cid",cid)
                                .andEqualTo("generic",generic)
                                .andEqualTo("searching",searching);
        return this.specParamMapper.selectByExample(example);
    }



    public List<SpecGroup> querySpecsByCid(Long cid) {
        // 查询规格组
        List<SpecGroup> groups = this.queryGroupsById(cid);
        groups.forEach(g -> {
            // 查询组内参数
            g.setParams(this.queryParams(g.getId(), null, null, null));
        });
        return groups;
    }
}
